<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">关注列表</p>
      </div>
      <!-- 搜索 -->
      <div class="g-search" style="padding-top: 20px" ref="searchBox">
        <!-- 信息区域 -->
        <div class="all_select" style="margin-top: 0">
          <!-- 订单编号 -->
          <div class="input_valye">
            <span class="demonstration">用户名称：</span>
            <input
              type="text"
              class="input"
              placeholder="请输入用户名称"
              v-model="searchValue.username"
              @keyup.enter="search" />
          </div>
          <!-- 订单状态 -->
          <div class="input_valye">
            <span class="demonstration">用户等级：</span>
            <el-select v-model="searchValue.vipRate" class="m-2" placeholder="请选择用户等级" @change="search">
              <el-option v-for="item in rate_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <!-- 订单状态 -->
          <div class="input_valye">
            <span class="demonstration">用户状态</span
            ><el-select v-model="searchValue.status" class="m-2" placeholder="请选择订单状态" @change="search">
              <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 表格按钮区域 -->
        <div class="table_function">
          <el-button class="solid" @click="massTexting" v-if="roleList.write">推送信息</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :header-cell-style="{'text-align': 'center'}"
          :show-overflow-tooltip="true"
          border>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="vipRate" label="会员等级" align="center">
            <template #default="item">
              <el-text v-if="item.row.vipRate == 0" class="mx-1" type="success">青铜</el-text>
              <el-text v-if="item.row.vipRate == 1" class="mx-1" type="default">白银</el-text>
              <el-text v-if="item.row.vipRate == 2" class="mx-1" type="warning">黄金</el-text>
              <el-text v-if="item.row.vipRate == 3" class="mx-1" type="primary">钻石</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="消费金额" align="center" />
          <el-table-column prop="status" label="用户状态" align="center">
            <template #default="item">
              <el-text v-if="item.row.status == 1" class="mx-1" type="success">活跃</el-text>
              <el-text v-if="item.row.status == 2" class="mx-1" type="primary">不活跃</el-text>
              <el-text v-if="item.row.status == 3" class="mx-1" type="warning">注销</el-text>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="total"
          @change="pageChange" />
      </div>
      <!-- 群发信息 -->
      <div class="messages" v-if="messagesShow">
        <div class="title1">
          <div class="title_mes">
            <el-icon size="20" color="#fff"> <Edit /> </el-icon>&nbsp;群发消息
          </div>
          <span class="close" @click="maskBtn1">✖</span>
        </div>
        <div class="content1" style="margin-top: 40px">
          <el-form ref="ruleFormRef" :model="GoodsformDate" label-width="90px" label-position="right" :rules="rules">
            <el-form-item label="推送类型:" prop="type">
              <el-select v-model="GoodsformDate.type" class="m-2" placeholder="请选择消息模板" @change="typeChange">
                <el-option v-for="item in type_options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="消息模板:" prop="templateId">
              <el-select
                v-model="GoodsformDate.templateId"
                class="m-2"
                placeholder="请选择消息模板"
                @change="typeChange1">
                <el-option v-for="item in template_options" :key="item.title" :label="item.title" :value="item.id">
                </el-option>
              </el-select>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="消息标题:" prop="title">
              <el-input
                v-model="GoodsformDate.title"
                class="form_input"
                maxlength="50"
                type="textarea"
                show-word-limit></el-input>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="短信内容:" prop="content">
              <el-input
                v-model="GoodsformDate.content"
                cols="30"
                rows="4"
                class="form_input"
                maxlength="300"
                type="textarea"
                show-word-limit></el-input>
              <span id="input_hint"></span>
            </el-form-item>
          </el-form>
          <div style="display: flex; align-items: center; font-size: 14px; color: #3d3d3d">
            <el-icon color="#116CF8" size="18"> <Warning /> </el-icon
            >&nbsp;发送时系统会自动在结尾追加平台名称，请勿重复添加
          </div>
          <div class="btn">
            <el-button class="hollow" @click="CancelPopUpBox">取消</el-button>
            <el-button class="solid" @click="plateformSure(ruleFormRef)">确定</el-button>
          </div>
        </div>
      </div>
      <!-- 遮罩层 -->
      <div id="mask1" v-if="mask" @click="maskBtn1"></div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, reactive, onBeforeUnmount} from 'vue';
import {RequestShopUser, RequesttemplateIds, SendMesToUser} from '@/api/path/index.js';

import moment from 'moment';
import {ElMessage} from 'element-plus';
import type {FormInstance} from 'element-plus';
import {Warning, Edit, User} from '@element-plus/icons-vue';
import useAuthorize from '@/hooks/authorize';
let roleList = useAuthorize();
const ruleFormRef = ref<FormInstance>();
// 推送消息数据
const GoodsformDate = ref({
  templateId: '',
  type: '',
  content: '',
  title: '',
});
// 表单规则
const rules = reactive({
  type: [{required: true, message: '请选择推送类型', trigger: 'change'}],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  templateId: [{required: true, message: '请输入消息模板', trigger: 'change'}],
  content: [{required: true, message: '请输入消息内容', trigger: 'blur'}],
  title: [{required: true, message: '请输入消息标题', trigger: 'blur'}],
});
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数
const deliverShow = ref(false); //控制发货显示
const mask = ref(false); //控制遮罩层显示
const orderShow = ref(false); //控制查看订单显示
const plateformShow = ref(false); //控制推送信息显示
const messagesShow = ref(false); //控制群发显示
const order = ref<any>([]); //订单数组
const radio = ref('');
const shopId = Number(localStorage.getItem('ShopId'));
interface RestaurantItem {
  value: string;
  link: string;
}

const status_list = ref<any>([]); //暂时存储状态
const ids = ref<any>([]);
/**
 * 表格复选框选中事件
 */
const handleSelectionChange = (selection: any) => {
  ids.value = [];
  for (let i = 0; i < selection.length; i++) {
    ids.value.push(selection[i].id);
  }
};
/************************************  群发消息  ************************************/
const massTexting = () => {
  if (ids.value.length == 0) {
    ElMessage.error('请选择接收消息的对象');
  } else {
    mask.value = true;
    messagesShow.value = true;
  }
};

/**
 * 根据推送类型获取模板
 */
const template_options = ref<any>([]);
const typeChange = async () => {
  const a = await RequesttemplateIds(GoodsformDate.value.type);
  template_options.value = a.resultObj;
};

const typeChange1 = async (value: number) => {
  template_options.value.forEach((item: any) => {
    if (item.id == value) {
      GoodsformDate.value.content = item.content;
    }
  });
};

/**
 * 推送类型
 */
const type_options = [
  {
    value: 0,
    label: '支付通知',
  },
  {
    value: 1,
    label: '物流通知',
  },
  {
    value: 2,
    label: '平台公告',
  },
  {
    value: 3,
    label: '优惠促销',
  },
];

/**
 * 群发消息确认
 */
const plateformSure = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      const a = await SendMesToUser({
        ids: ids.value,
        templateId: GoodsformDate.value.templateId,
        content: GoodsformDate.value.content,
        type: GoodsformDate.value.type,
        title: GoodsformDate.value.title,
        shopId: shopId,
      });
      if (a.msg == '操作成功！') {
        ElMessage.success('发送成功');
        messagesShow.value = false;
        mask.value = false;
      } else {
        ElMessage.error('发送失败，请重试！');
      }
    }
  });
};
/************************************  弹出框关闭  ************************************/
const CancelPopUpBox = () => {
  mask.value = false;
  messagesShow.value = false;
  GoodsformDate.value = {
    templateId: '',
    type: '',
    content: '',
    title: '',
  };
};

/**
 * 分页
 */
const pageChange = async (val: number) => {
  requestShopUser();
};
// 挂载
onMounted(() => {
  requestShopUser();
  handleResize();
  window.addEventListener('resize', handleResize);
});
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
  console.log('Search Box height11111111111111111111111111111:', searchBoxHeight);
};

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
/**
 * 获取订单信息
 */
const requestShopUser = async () => {
  const a = await RequestShopUser(searchValue.value);
  if (a.resultObj == null) {
    tableData.value = [];
    total.value = 0;
  } else {
    tableData.value = a.resultObj.users;
    total.value = a.resultObj.count;
  }
};
// 搜索参数
const searchValue = ref({
  shopId: shopId,
  username: '',
  vipRate: '',
  status: '',
  page: 1,
  rows: 10,
});
/**
 * 状态选择器
 */
const status_options = [
  {
    value: 1,
    label: '活跃',
  },
  {
    value: 2,
    label: '注销',
  },
  {
    value: 3,
    label: '冻结',
  },
];
/**
 * 状态选择器
 */
const rate_options = [
  {
    value: 0,
    label: '青铜',
  },
  {
    value: 1,
    label: '白银',
  },
  {
    value: 2,
    label: '黄金',
  },
  {
    value: 3,
    label: '钻石',
  },
];
/**
 * 搜索
 */
const search = async () => {
  searchValue.value.page = 1;
  requestShopUser();
};
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    shopId: shopId,
    username: '',
    vipRate: '',
    status: '',
    page: 1,
    rows: 10,
  };
  radio.value = '0';
  requestShopUser();
};
/**
 * 遮罩层数据
 */
const maskBtn1 = () => {
  deliverShow.value = false;
  mask.value = false;
  plateformShow.value = false;
  status_list.value = '';
  messagesShow.value = false;
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

.table {
  height: calc(100% - v-bind(tablelistHeight)) !important;
}

::v-deep .el-table--fit {
  height: calc(100% - 150px) !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}

.table {
  overflow: hidden;
  padding: 0 10px;

  .table_function {
    margin-top: 20px;
  }
}

.el-form-item :deep(.el-input-group__prepend) {
  width: 10px;
  background-color: #116cf8;
  color: #fff;
}

.el-form-item :deep(.el-upload--picture-card) {
  height: 100px;
  width: 100px;
  opacity: 0;
}

// 推送消息
.plateform,
.messages {
  width: 600px;
  height: 500px;
  position: absolute;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-left: -300px;
  margin-top: -250px;
  z-index: 99;
  background: #fff;
}

.btn {
  width: 150px;
  position: absolute;
  right: 20px;
  bottom: 40px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 150px;
}

:deep(.el-drawer.rtl) {
  background: #f5f9ff;
  width: 750px !important;
}

:deep(.el-overlay) {
  z-index: 40 !important;
  padding: static;
}

:deep(.is-process) {
  color: #409eff;
}

:deep(.is-process .el-step__icon.is-text) {
  border: 2px solid #409eff;
  background: #409eff;
  color: #fff;
}

:deep(.is-finish .el-step__line) {
  background: #409eff;
}

.el-table .warning-row {
  background: #44a2ff !important;
}
</style>
